package oojo.data.impl.exec;

import java.util.Set;
import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import oojo.data.impl.BaseFilter;
import oojo.data.spec.Filter;

public class FetchFilter extends BaseFilter {

    private static final Logger logger = LoggerFactory.getLogger(FetchFilter.class);
    
    public Class<?> getFilterClass() {
        return Filter.class;
    }

    @Override
    public String createCriteria(Filter spec) {
        logger.debug("---> createCriteria(spec)");
        
        String value = spec.getValue();
        Set<String> properties = spec.getProperties();
        StringBuilder sb = new StringBuilder();
        
        if (value != null) {
            for (Iterator<String> it = properties.iterator(); it.hasNext();) {
                String property = it.next();
                sb.append("e.").append(property).append(" like :").append(property.replace('.', '_'));
    
                if (it.hasNext()) {
                    sb.append(" or ");
                }
            }
        }
        
        return sb.toString();
    }

    @Override
    public void configCriteria(Filter spec, javax.persistence.Query query) {
        logger.debug("---> configCriteria(spec, query)");
        
        String value = spec.getValue();
        Set<String> properties = spec.getProperties();
        
        if (value != null) {
            boolean starts = (spec.getMode() & Filter.STARTS) > 0;
            boolean ends = (spec.getMode() & Filter.ENDS) > 0;
            value = (!starts ? "%" : "") + value + (!ends ? "%" : "");
            
            for (String property : properties) {
                query.setParameter(property.replace('.', '_'), value);
            }
        }
    }
}
